import { useState } from 'react';
import { getPathByEnv } from '@/utils';
import { request } from '@/request';
import { useGlobalVar } from '@/hooks';

const avators = new Array(10)
   .fill(1)
   .map((v, i) => `avatars/avatar${i + 1}.svg`);

const Avatar = () => {
   const { user, refetchUser } = useGlobalVar();

   const [avatar, setAvatar] = useState(user.avatar);
   const handleChangeAvatar = (avatar: string) => {
      setAvatar(avatar);
   };

   const handleSubmit = () => {
      request('/user/avatar', {
         method: 'POST',
         data: {
            avatar,
         },
         showSuccess: true,
         success: () => {
            refetchUser();
         },
      });
   };

   return (
      <>
         <div className="box mt-4 p-4 grid grid-cols-4 gap-2">
            {avators.map((item) => {
               let cls = 'w-14 h-14 rounded-sm mr-4 overflow-hidden shadow-md';
               if (item === avatar)
                  cls += ' border-2 bg-indigo-100 border-indigo-500';
               return (
                  <div
                     key={item}
                     className={cls}
                     onClick={handleChangeAvatar.bind(null, item)}
                  >
                     <img src={getPathByEnv(item)} />
                  </div>
               );
            })}
         </div>
         <div
            className="btn fixed bottom-10 right-4 left-4"
            onClick={handleSubmit}
         >
            确认修改
         </div>
      </>
   );
};
export default Avatar;
